package com.csht.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csht.model.CshtNotice;
import com.csht.model.CshtUser;
import com.csht.page.PagerModel;
import com.csht.page.SystemContext;
import com.csht.service.CshtNoticeService;
import com.csht.vo.index.user.CshtUserVo;

/**
 * 消息通知
 * @author chenhuiyan
 *
 */
@Controller
@RequestMapping(value = "/toMy")
public class NoticeController {
	
	@Autowired
	private CshtNoticeService cshtNoticeService;
	
	/**
	 * 个人中心－消息通知页面
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/notice")
	public String notice(ModelMap model, HttpServletRequest request) throws Exception{
		CshtUser cshtUser = (CshtUser) request.getSession().getAttribute("loginUser"); //获取登录用户
		Map<String, Integer> res = new HashMap<String, Integer>();
		res.put("userId", cshtUser.getUserId());
		res.put("offset", SystemContext.getOffset()); //偏移量
		res.put("noticePageSize", SystemContext.getNoticePageSize()); //每页数量
		PagerModel<CshtNotice> pagerModel = cshtNoticeService.getNoticeByUserId(res);
		model.addAttribute("pagerModel", pagerModel);
		return "/toMy/notice";
	}
	
	/**
	 * 根据消息通知id查询消息并更新消息状态已读
	 * @param noticeId
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/getNoticeById")
	public Map<String, CshtNotice> getNoticeById(@RequestParam(name = "noticeId") Integer noticeId, 
			HttpServletRequest request) throws Exception{
		CshtUserVo cshtUserVo = (CshtUserVo) request.getSession().getAttribute("cshtUserVo"); //获取登录用户封装类
		Map<String, CshtNotice> res = new HashMap<String, CshtNotice>();
		CshtNotice cshtNotice = cshtNoticeService.getNoticeById(noticeId); //查询消息
		cshtNoticeService.updateNoticeIsReadyById(noticeId); //更新消息状态已读
		cshtUserVo.setUserNoticeNumber(cshtNoticeService.getNoticeNumberByUserId(cshtUserVo.getUserId())); //更新用户封装类消息数量
		request.getSession().setAttribute("cshtUserVo", cshtUserVo);
		res.put("notice", cshtNotice);
		return res;
	}

}
